import { Client as WsRpcClient } from "rpc-websockets"
export class RpcClient{
    private static wsClient:WsRpcClient

    private static started:boolean

    /**
     * 连接到ws服务
     * @param wsUrl ws地址,类似:ws://127.0.0.1:10020
     */
    public static start(wsUrl:string):void{
        if(this.started){
            console.log('rpcClient is already connect!,so do nothing')
            return 
        }
        this.wsClient=new WsRpcClient(wsUrl)
        this.wsClient.on('open',()=>{
            console.info('rpcClient connect to rpcServer')
            this.started=true
        })
        this.wsClient.on('error',err =>{
            this.started=false
            console.error('rpcClient happend error',err)
        })
        this.wsClient.on('close',()=>{
            this.started=false
            console.info('rpcClient had closed')
        })

    }
    /**
     * 关闭wsClient连接
     */
    public static close():void{
        if(this.started){
            console.info('rpcClient close ')
            this.wsClient.close()
        }
    }

    /**
     * 调用rpc服务
     * @param methodName 服务名
     * @param params 参数
     * @returns 返回promise对象
     */
  public static callMethod(methodName:string,...params:Array<any>):Promise<unknown>{
      if(this.started){
          return this.wsClient.call(methodName,params)
      } 
      return Promise.reject("the client don't connected" )
  }


}